package com.fzq.flowable_demo.service;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProcessDiagramServiceFinish {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    /**
     * 生成高亮流程图（显示当前节点）
     */
    public void generateDiagram(HttpServletResponse response, String processInstanceId) throws IOException {
        // 获取流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        // 获取BPMN模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());

        // 获取当前活动节点
        List<String> activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);

        // 获取高亮的连线
        List<String> highLightedFlows = getHighlightedFlows(processInstanceId);

        // 获取历史活动节点（高亮已完成的）
        List<HistoricActivityInstance> historicActivities = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();

        List<String> highLightedActivities = historicActivities.stream()
                .map(HistoricActivityInstance::getActivityId)
                .collect(Collectors.toList());

        // 生成流程图
        ProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();
        InputStream imageStream = diagramGenerator.generateDiagram(
                bpmnModel,
                "png",                    // imageType: 图片格式
                highLightedActivities,    // 高亮的活动节点
                highLightedFlows,  // 高亮的连线
                "宋体",                   // 活动字体
                "宋体",                   // 标签字体
                "宋体",                   // 注解字体
                null,                     // 类加载器
                1.0,                      // scaleFactor: 缩放因子
                true                      // drawSequenceFlowNameWithNoLabelID: 是否绘制连线名称
        );

        // 输出到响应
        response.setContentType("image/png");
        response.setHeader("Content-Disposition",
                "attachment; filename=process-diagram.png");

        IOUtils.copy(imageStream, response.getOutputStream());
        response.flushBuffer();
    }

    /**
     * 生成已完成流程的流程图
     */
    public void generateCompletedDiagram(HttpServletResponse response, String processInstanceId) throws IOException {
        HistoricProcessInstance historicProcessInstance = historyService
                .createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());

        // 获取所有历史活动节点
        List<HistoricActivityInstance> historicActivities = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();
        //获取高亮的连线
        List<String> highLightedFlows = getHighlightedFlows(processInstanceId);


        List<String> highLightedActivities = historicActivities.stream()
                .map(HistoricActivityInstance::getActivityId)
                .collect(Collectors.toList());

        ProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();
        InputStream imageStream = diagramGenerator.generateDiagram(
                bpmnModel,
                "png",                    // imageType: 图片格式
                highLightedActivities,    // 高亮的活动节点
//                Collections.emptyList(),  // 高亮的连线
                highLightedFlows,
                "宋体",                   // 活动字体
                "宋体",                   // 标签字体
                "宋体",                   // 注解字体
                null,                     // 类加载器
                1.0,                      // scaleFactor: 缩放因子
                true                      // drawSequenceFlowNameWithNoLabelID: 是否绘制连线名称
        );
        response.setContentType("image/png");
        IOUtils.copy(imageStream, response.getOutputStream());
        response.flushBuffer();
    }

    /**
     * 获取高亮的连线ID列表
     */
    private List<String> getHighlightedFlows(String processInstanceId) {
        List<HistoricActivityInstance> historicActivities = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .activityType("sequenceFlow")  // 只查询连线类型的活动
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();

        return historicActivities.stream()
                .map(HistoricActivityInstance::getActivityId)
                .collect(Collectors.toList());
    }

}
